import axios from 'axios'

const API_URL = 'http://localhost:8080/api/personnel/'

axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }
  return config
})

class PersonnelService {
  async getAll(params = {}) {
    try {
      const response = await axios.get(API_URL + 'search', { 
        params: {
          name: params.name || '',
          position: params.position || '',
          gender: params.gender || '',
          page: params.page || 0,
          size: params.size || 10
        }
      });

      if (!response.data.content) {
        return {
          content: Array.isArray(response.data) ? response.data : [],
          totalElements: Array.isArray(response.data) ? response.data.length : 0,
          totalPages: 1,
          size: params.size || 10,
          number: params.page || 0
        };
      }
      return response.data;
    } catch (error) {
      console.error('Error fetching personnel:', error);
      throw this.handleError(error);
    }
  }

  async getById(id) {
    const response = await axios.get(API_URL + id)
    return response.data
  }

  async create(personnel) {
    const response = await axios.post(API_URL, personnel)
    return response.data
  }

  async update(id, personnel) {
    const response = await axios.put(API_URL + id, personnel)
    return response.data
  }

  async delete(id) {
    const response = await axios.delete(API_URL + id)
    return response.data
  }

  handleError(error) {
    if (error.response && error.response.data) {
      return {
        message: error.response.data.message || '操作失败',
        status: error.response.status
      };
    }
    return {
      message: error.message || '网络错误',
      status: 500
    };
  }
}
export default new PersonnelService()
